# -*- coding: utf-8 -*-

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session

from app import log
from app import config

import sqlalchemy.pool as pool
from sqlalchemy.pool import NullPool , QueuePool
# from sqlalchemy import create_engine, exc, text, cast, Numeric, and_
from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.automap import automap_base

from sqlalchemy.engine.url import make_url,URL
from sqlalchemy.sql import column
from datetime import datetime, timedelta

LOG = log.get_logger()

def get_engine(uri):
    LOG.info('Connecting to database..')
    options = {
        'pool_recycle': 3600,
        'pool_size': 10,
        'pool_timeout': 30,
        'max_overflow': 30,
        'echo': config.DB_ECHO,
        'execution_options': {
            'autocommit': config.DB_AUTOCOMMIT
        }
    }
    return create_engine(uri, **options)


db_session = scoped_session(sessionmaker())
engine = get_engine(config.DATABASE_URL)
LOG.info('automap_base start..')
db_session.configure(bind=engine)

metadata = MetaData()
# add table you need use
load_tables = [

]

metadata.reflect(engine, only=load_tables)

AutoBase = automap_base(metadata=metadata)

AutoBase.prepare()
LOG.info('automap_base done..')
# creat tables
def init_session():
    from app.model import Base
    Base.metadata.create_all(engine)
